namespace ES.Controllers
{
    using System.Linq;
    using System.Web.Mvc;
    using ES.Models;

    public class BaseController : Controller
    {
        public Customer CurrentCustomer;

        public SmDbDataContext Db = new SmDbDataContext();

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            ViewBag.CategoryList = Db.Categories.OrderBy(d => d.OrderNumber).ToList();
            var customer = (Session["loginkey"] as Customer);
            if (filterContext.ActionDescriptor.ActionName != "Login")
                if (customer == null)
                {
                    filterContext.Result = RedirectToAction("Login", "My");
                    return;
                }
            CurrentCustomer = customer;
        }

        protected static IQueryable<Product> AddFilter(DefaultFilter filter, IQueryable<Product> list)
        {
            if (filter != null)
            {
                if (!string.IsNullOrEmpty(filter.SearchString))
                {
                    list =
                        list.Where(
                            d =>
                            d.Title.Contains(filter.SearchString) || d.Model.Contains(filter.SearchString) ||
                            d.Description.Contains(filter.SearchString));
                }
                if (filter.SortDir == SortDir.Asc)
                {
                    if (filter.Sort == ProductColumnEnum.Title)
                        list = list.OrderBy(d => d.Title);
                    if (filter.Sort == ProductColumnEnum.Price)
                        list = list.OrderBy(d => d.Price);
                    if (filter.Sort == ProductColumnEnum.Model)
                        list = list.OrderBy(d => d.Model);
                }
                else
                {
                    if (filter.Sort == ProductColumnEnum.Title)
                        list = list.OrderByDescending(d => d.Title);
                    if (filter.Sort == ProductColumnEnum.Price)
                        list = list.OrderByDescending(d => d.Price);
                    if (filter.Sort == ProductColumnEnum.Model)
                        list = list.OrderByDescending(d => d.Model);
                }
            }
            return list;
        }
    }
}